# -*- coding: utf-8 -*-
"""Helper utilities and decorators."""
from flask import flash, url_for
import glob
import requests, logging
import json
import datetime as dt
from xml.dom.minidom import parse
import xml.dom.minidom
from wechatpy.pay import WeChatPay
from wechatpy.exceptions import WeChatPayException
from wechatpy import WeChatClient

appid = 'wx5bf47679c84ef3c8'
secret = '5d3631653759f2a3307793414e87bc62'
mch_id = '1342338301'
api_key = 'duobaohui618duobaohui618duobao88'
host = 'http://flashsales.tangle-up.top'
pay = WeChatPay(appid, api_key, mch_id, mch_cert='/home/sale/cert/apiclient_cert.pem', mch_key='/home/sale/cert/apiclient_key.pem')

def flash_errors(form, category='warning'):
    """Flash all errors for a form."""
    for field, errors in form.errors.items():
        for error in errors:
            flash('{0} - {1}'.format(getattr(form, field).label.text, error), category)

def getPicNum(id):
    return len(glob.glob(r'./AmoluoSale/static/img/items/'+str(id)+'/[0-9].*'))+len(glob.glob(r'./AmoluoSale/static/img/items/'+str(id)+'/[0-9][0-9].*'))

def getToken(code):
    getTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"%(appid, secret, code)
    print getTokenUrl
    r = requests.get(getTokenUrl)
    print r.json()
    if r.status_code == 200:
        openid = r.json().get('openid')
        access_token = r.json().get('access_token')
        print openid,access_token
        if openid and access_token:
            return openid, access_token
        else:
            return None, None
    else:
        return None, None

def getUserInfoFromToken(openid, access_token):
    getUserUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"%(access_token, openid)
    print getUserUrl
    r = requests.get(getUserUrl)
    if r.status_code == 200:
        userInfo = r.json()
        print userInfo
        return userInfo if not userInfo.get('errcode') else None
    else:
        return None

def validToken(openid, access_token):
    url = "https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s"%(access_token, openid)
    r = requests.get(url)
    if r.status_code == 200 and r.json().get('errcode') == 0:
        return True
    else:
        return False

def sendBuyNotify(openid, data):
    client = WeChatClient(appid, secret)
    token = client.fetch_access_token()
    access_token = token['access_token']
    jsonData = {}
    jsonData['touser'] = openid
    jsonData['template_id'] = 'JDuLcQ22vGbQF4SvotqcsDmh5UWV19vqVvYIhEGbvE0'
    jsonData['url'] = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5bf47679c84ef3c8&redirect_uri=http%3a%2f%2fflashsales.tangle-up.top%2fmyOrders&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
    jsonData['topcolor'] = '#FF0000'
    jsonData['data'] = data

    jsonData = json.dumps(jsonData)

    print jsonData

    url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='+access_token
    print url
    r = requests.post(url, data = jsonData)
    print r.text

def sendDeliverNotify(openid, data):
    client = WeChatClient(appid, secret)
    token = client.fetch_access_token()
    access_token = token['access_token']
    jsonData = {}
    jsonData['touser'] = openid
    jsonData['template_id'] = '-7V97ZcWnOHXvL67L_ec40hxACMq1-Kmi-2lfKbFveA'
    jsonData['url'] = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5bf47679c84ef3c8&redirect_uri=http%3a%2f%2fflashsales.tangle-up.top%2fmyOrders&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
    jsonData['topcolor'] = '#FF0000'
    jsonData['data'] = data

    jsonData = json.dumps(jsonData)

    print jsonData

    url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='+access_token
    print url
    r = requests.post(url, data = jsonData)
    print r.text

def createOrder(detail, total_fee, user_id, notify_url, attach = None):
    params=None
    try:
        result=pay.order.create(trade_type = 'JSAPI', body = detail, total_fee = total_fee, notify_url = host+notify_url, user_id = user_id, time_expire = (dt.datetime.now()+dt.timedelta(minutes = 10)), attach=attach)
        params=pay.jsapi.get_jsapi_params(result['prepay_id'])
    except WeChatPayException as e:
        print e, e.request, e.response, e.response.text
    print params
    return params

def closeOrder(out_trade_no):
    pay.order.close(out_trade_no)

def getUserBySDK(openid):
    client = WeChatClient(appid, secret)
    user = client.user.get(openid)
    print user
    return user

def getTokenBySDK():
    client = WeChatClient(appid, secret)
    return client.fetch_access_token()

def getJSTicket():
    client = WeChatClient(appid, secret)
    return client.jsapi.get_jsapi_ticket()
